'use strict';
import React, { Component, PropTypes, cloneElement } from 'react';
import { message, Modal, Pagination, Popconfirm, Button, Progress } from 'antd';
import { connect } from 'dva';
import step1Create from './step1'
import step2Create from './step2'
import step3Create from './step3'
class DataImport extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }
    componentWillMount() {
        const { daoName, defaultParamVals } = this.props
        if (defaultParamVals) {
            this.props.dispatch({
                type: `${daoName}_DataImport/setParams`,
                payload: { params: defaultParamVals }
            });
        }
    }
    componentWillReceiveProps(nextProps) {
        const { importing, daoName, fileName, timer } = this.props
    
        if (nextProps.importing && !importing && timer === 0) {
            const dataProgress = () => {
                this.props.dispatch({
                    type: `${daoName}_DataImport/dataProgress`,
                    payload: { fileName }
                });
            }
            let timer2 = window.setInterval(dataProgress, 1000);
            this.props.dispatch({
                type: `${daoName}_DataImport/setImporting`,
                payload: { importing: true, timer: timer2 }
            });
        }
    }
    getParams(){
        const step1 = this.refs.step1.getWrappedInstance()
        let formData1 = step1.getFormData()
        if (!formData1) {
            return;
        }
        Object.keys(formData1).map(key => {
            if (formData1[key] instanceof Array) {
                const l = formData1[key].length
                formData1[key] = formData1[key][l - 1]
            }
        })
        return formData1
    }
    nextStep1(execImport) {
        if (this.props.fileName === "") {
            message.warn("请选择要导入的文件！")
            return;
        }
        const params = this.getParams()
        let { controls, importName, daoName, importMode, keys, step, fileName, hasColHeader, formData } = this.props;
        let newParams = { ...params }
        delete newParams.select_sheetName
        const importInfo = {
            ImportName: importName,
            DaoName: daoName,
            FilePath: fileName,
            SheetName: params.select_sheetName,
            Mode: importMode,
            Params: newParams,
            Keys: keys,
            HasColHeader: hasColHeader,
        }
        this.props.dispatch({
            type: `${daoName}_DataImport/fetchDataMap`,
            payload: { controls, importInfo, execImport }
        });
    }
    import() {
        let step = this.props.step;
        this.importData()
    }
    deleteFile() {
        const daoName = this.props.daoName
        let fileName = this.props.fileName
        if (fileName === "") {
            return
        }
        this.props.dispatch({
            type: `${daoName}_DataImport/deleteUploadFile`,
            payload: { fileName }
        });
    }
    importData() {
        if (this.props.fileName === "") {
            message.warn("请选择要导入的文件！")
            return;
        }
        let formData2
        if (this.props.step === 2) {
            const step2 = this.refs.step2.getWrappedInstance()
            formData2 = step2.getFormData()
            if (!formData2) {
                return;
            }
        }
        let errorDatas = this.props.errorDatas
        if (this.props.step === 3) {
            const step3 = this.refs.step3.getWrappedInstance()
            let isOk = step3.isEditValid()
            if (!isOk && !this.props.ignoreErr) {
                message.warn("存在数据验证错误，请修改；或者忽略这些错误！", 5);
                return;
            }
            errorDatas = step3.getErrorDatas()
        }
        const { importName, daoName, importMode, keys, step, fileName, hasColHeader, dataMaps, dataMapsChange, params, columns, ignoreErr, isNewMap, attachParams, forbidConvert, saveByDao } = this.props;
        let dMap = null
        let newDataMaps = null
        if (dataMapsChange) {
            newDataMaps = [...dataMaps]
            Object.keys(formData2).forEach((key) => {
                for (let i = 0; i < newDataMaps.length; i++) {
                    if (key === newDataMaps[i].DestColName) {
                        dMap = newDataMaps[i]
                        break;
                    }
                }
                let index = formData2[key];
                index = index.indexOf("@") === 0 ? -1 : Number(index);
                dMap.SrcColIndex = index;
                let sName = ""
                if (index === -1) {
                    sName = formData2[key]
                } else if (index >= 0) {
                    sName = columns[index]
                }
                dMap.SrcColName = sName;
            });
        }
        let params2 = params
        if (!params2.select_sheetName){
            params2 = this.getParams()
        }
        let newParams = { ...params2, ...attachParams }
        delete newParams.select_sheetName
        newParams = { ...newParams, }
        const importInfo = {
            ImportName: importName,
            DaoName: daoName,
            FilePath: fileName,
            SheetName: params2.select_sheetName,
            Mode: importMode,
            Params: newParams,
            Keys: keys,
            HasColHeader: hasColHeader,
            ForbidConvert: forbidConvert,
            SaveByDao: saveByDao
        }
        this.props.dispatch({
            type: `${daoName}_DataImport/dataImport`,
            payload: { importInfo: importInfo, ignoreErr, errorDatas, dataMaps: newDataMaps, isNewMap }
        });
    }
    prevStep() {
        let step = this.props.step;
        const daoName = this.props.daoName
        if (step == 3 && this.props.errorDatas.length > 0) {
            const step3 = this.refs.step3.getWrappedInstance()
            let isOk = step3.isEditValid()
            if (!isOk) {
                message.warn("存在数据验证错误,请修改！", 5);
                return;
            }
            const errorDatas = step3.getErrorDatas()
            this.props.dispatch({
                type: `${daoName}_DataImport/setErrorDatas`,
                payload: { errorDatas }
            });
        }
        step--;
        this.props.dispatch({
            type: `${daoName}_DataImport/setStep`,
            payload: { step }
        });
    }
    hideImportHandler() {
        const { daoName, step } = this.props
        this.deleteFile();
        if (step === 3) {
            this.props.dispatch({
                type: `${daoName}/reload`,
                payload: { daoName }
            });
        }
        this.props.dispatch({
            type: `${daoName}_DataImport/setDisplay`,
            payload: { display: false }
        });
    }
    render() {
        const { step, title, daoName, display, controls, paramNames, success, loading, importing, process, fileName, modelName, importName, isNewMap } = this.props;
        let stepName = "选择导入文件"
        if (step === 2) {
            stepName = "选择数据映射关系"
        } else if (step === 3) {
            stepName = "导入结果"
        }
        let modalTitle = <div>{title + "导入"}<span style={{ float: "right", paddingRight: "100px" }}>{stepName}</span></div>
        let width = 400
        if (step === 2 && controls.length > 5) {
            width = 800
        } else if (step === 3) {
            width = 800
        }
        const Step1 = step1Create(daoName)
        const Step2 = step2Create(daoName)
        const Step3 = step3Create(daoName)
        let content = <div><Step1 ref="step1" importName={importName} modelName={modelName} daoName={daoName} controls={controls} paramNames={paramNames} visible={step === 1} />
            <Step2 ref="step2" modelName={modelName} daoName={daoName} controls={controls} paramNames={paramNames} visible={step === 2} />
            <Step3 ref="step3" modelName={modelName} daoName={daoName} controls={controls} paramNames={paramNames} visible={step === 3} /></div>
        if (importing) {
            content = <div style={{ textAlign: "center", verticalAlign: "middle" }}><Progress type="circle" percent={process.percent} format={percent => `${percent} %`} /></div>
            modalTitle = <div>导入进度:{process.msg}</div>
        }
        return (
            <div>
                <Modal title={modalTitle} width={width} visible={display} onOk={this.import.bind(this)} onCancel={this.hideImportHandler.bind(this)} maskClosable={false}
                    footer={[
                        <Button disabled={step === 1 || step === 3} loading={loading || importing} key="prevStep" type="primary" onClick={this.prevStep.bind(this)}>上一步</Button>,
                        <Button disabled={step > 1 || !isNewMap} loading={loading || importing} key="nextStep" type="primary" onClick={this.nextStep1.bind(this, false)}>下一步</Button>,
                        <Button disabled={fileName === "" || step === 1 && isNewMap || (step === 3 && success)} loading={loading || importing} key="import" type="primary" onClick={this.import.bind(this)}>导入</Button>,
                        <Button key="close" type="ghost" onClick={this.hideImportHandler.bind(this)}>关闭</Button>
                    ]}
                >
                    {content}
                </Modal>
            </div>
        );
    }
}
DataImport.propTypes = {
    importName: PropTypes.string,
    modelName: PropTypes.string,
    daoName: PropTypes.string,
    importMode: PropTypes.string,
    controls: PropTypes.array,
    paramNames: PropTypes.array,
    attachParams: PropTypes.object,
    defaultParamVals: PropTypes.object,
    keys: PropTypes.array,
    title: PropTypes.string,
    forbidConvert: PropTypes.bool,
    saveByDao: PropTypes.bool
};
DataImport.defaultProps = {
    importName: "",
    daoName: "",
    importMode: "",
    controls: [],
    paramNames: [],
    attachParams: {},
    defaultParamVals: null,
    keys: [],
    title: "",
    forbidConvert: false,
    saveByDao: false
};
export default function dataImportCreate(daoName) {
    function mapStateToProps(state) {
        const dimodel = `${daoName}_DataImport`
        const { display, step, fileName, hasColHeader, dataMaps, dataMapsChange, params, columns, ignoreErr, errorDatas, isNewMap, success, importing, process, timer } = state[dimodel];
        return {
            loading: state.loading.models[dimodel],
            display, step, fileName, hasColHeader, dataMaps, dataMapsChange, params, columns, ignoreErr, errorDatas, isNewMap, success, importing, process, timer
        }
    }
    return connect(mapStateToProps)(DataImport);
}
